<template>
  <div class='m-courseSignUp'>
    <div class='m-courseSignUp_top'>
      <div class='list'>
        <div class='item'>
          <div class="grid-content">
            <div class='name' style='margin-right: 20px;'>课程名称:</div><span class='value'>{{ lessonName }}，价格：{{ aGoods[0] ? aGoods[0].aPayment : 0 }}</span>
            <el-button v-if='!isUpdate' size='mini' type='primary' @click='showLessonDialog'>选择课程</el-button>
          </div>
        </div>
        <div class='item'>
          <div class="grid-content">
            <div class='name'>总费用:</div><span class='value'>{{ (aGoods[0] ? aGoods[0].aPayment : 0) +  price }}元</span>
            <el-button v-if='!isUpdate' size='mini' type='primary' @click='showPriceDialog'>添加费用</el-button>
          </div>
        </div>
        <div class='item'>
          <div class="grid-content">
            <div class='name'>销售员:</div><span class='value'>{{ sellerName || '暂无' }}</span>
            <el-button v-if='!isUpdate' size='mini' type='primary' @click='showStaffDialoog'>选择销售员</el-button>
          </div>
        </div>
      </div>
      <div class="goods-item" v-show='isShowGoods && aGoods.length === 2'>
        <div class="key">其他费用:</div>
        <ul class='value'>
          <li class="item">
            <span>费用名称</span><span>费用</span><span>操作</span>
          </li>
          <li class="item" v-for='(v, i) in aGoods' :key='v.sku_id' v-if='i === 1'>
            <span>{{ v.name }}</span><span>{{ v.aPayment }}</span><span v-if='!isUpdate' @click='closeGood' class='el-icon-close'></span>
          </li>
        </ul>
      </div>
    </div>

    <div class='m-courseSignUp_bottom'>
      <el-form class="form"  :inline='true' label-width="120px" >
        <el-form-item class='maxwidth' label="手机号码：">
          <el-input v-if='!isUpdate' style='margin-right: 20px;' type="number" placeholder="请输入手机号码" v-model="phone"></el-input>
          <span v-else>{{ phone }}</span>
          <el-button v-if='!isUpdate' type='primary' @click='getUserInfo'>导入客户资料</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 用户属性列表 -->
      <ul  class='m-courseSignUp_userAttrs'>
        <div class="item">
          <span class="key">客户名称：</span>
          <span class="value">{{ buyer_name || '暂无' }} </span>
        </div>
        <li
          class='item'
          v-for='v in userAttrList'
          :key='v.id'
          v-if='v.content'
        >
          <span class="key">{{ v.name }}：</span>
          <span class="value">{{ v.content }}</span>
        </li>
      </ul>

      <!-- 必选 -->
      <el-form :inline='true' label-width="120px" v-if='!isUpdate'>
        <el-form-item class='createTheFormItem' v-for='(attr, attrIndex) in attrList' :key='attr.id' :label='attr.name + "："'  >
          <!-- 选择分类 -->
          <div v-if='attr.value_type === "0"' :class='attr.is_require === "1" ? "w100" : "m-courseSignUp_autoAttr"'>
            <el-checkbox-group v-model="attr.selects">
              <el-checkbox v-for='classItem in attr.classes' 
                :key='classItem.id' :label="classItem.id">
                <span>{{ classItem.name }}</span>
                <!-- 再显示子分类 -->
                <el-select v-if='classItem.child && classItem.child.length'
                  v-model='classItem.selects'
                  multiple collapse-tags clearable
                >
                  <el-option
                    v-for='(item) in classItem.child'
                    :key='item.id'
                    :label='item.name'
                    :value='item.id'
                  />
                </el-select>
              </el-checkbox>
            </el-checkbox-group>
            <i v-if='attr.is_require !== "1"' class='el-icon-close' @click='closeAutoAttr(attrIndex)'></i>
          </div>
          <!-- 输入类型 -->
          <div v-else  :class='attr.is_require === "1" ? "w100" : "m-courseSignUp_autoAttr"'>
            <el-input :class='attr.is_require === "1" ? "form-content" : ""' type='text' v-model.trim='attr.classes[0].name' />
            <i v-if='attr.is_require !== "1"' class='el-icon-close' @click='closeAutoAttr(attrIndex)'></i>
          </div>
        </el-form-item>
      </el-form>

      <el-form class="form"  :inline='true' label-width="120px"  v-if='!isUpdate'>
        <el-form-item label="学员属性：" class='maxwidth'>
          <attr-list aType='2' ref='attrList' :isShowSelectBox='false'  @getSku='getSku' />
        </el-form-item>
        <div style='width: 100%;'>
          <el-button v-if='!isUpdate' @click='create' type="primary">{{ type === 'add' ? '添加报名' : '修改报名信息' }}</el-button>
        </div>
      </el-form>

      <!-- 报名详情 -->
      <el-form class="form"  :inline='true' label-width="120px"  v-if='isUpdate'>
        <el-form-item label='报名历史：'>
          <a-table  :data='historyData' :cols='tableKeys'></a-table>
        </el-form-item>
      </el-form>
    </div>

    <lesson-dialog ref='lessonDialog' @getData='getLessonTitle' />
    <price-dialog ref='priceDialog' @getData='getPrice' />
    <staff-dialog ref='staffDialog' @getData='getStaff' />
    <sku-dialog ref='skuDialog' :data='skuData' @getData='getSkuFromDialog' />
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import AttrList from '@/components/business/List'
import lessonDialog from '@/module/business/course_detail_lessonDialog'
import priceDialog from '@/module/business/course_detail_priceDialog'
import staffDialog from '@/components/business/StaffsDialog'
import skuDialog from '@/module/business/course_signUp_selectSkuDialog'
import attrMixin from '@/mixins/attrs'
import { orderStatus } from '@/api/order'

export default {
  name: 'courseSignup',

  components: {
    AttrList,
    lessonDialog,
    priceDialog,
    skuDialog,
    staffDialog
  },

  mixins: [attrMixin],

  data() {
    const filterStatus = (value) => {
      const _value = parseInt(value, 10)
      let data = orderStatus.filter(v => v.type === _value)
      data = data[0] ? data[0].desc : '订单状态异常'
      return data
    }
    const filterTime = window.$tools.filterTime
    return {
      id: '',
      // 课程属性
      lessonName: '',
      lessonSku_id: '',
      lessonPrice: '',
      phone: '',
      seller: '',
      sellerName: '',
      type: 'add',
      isUpdate: false,
      userId: '',
      aGoods: [],
      sellerList: [],
      ifRequesting: false,
      price: 0,
      buyer_name: '',
      // 是否显示课程名称和总费用
      isShowGoods: true,
      // 用户属性列表
      userAttrList: [],
      skuData: [],
      skuOpenType: '',
      selectSkuId: '',
      isHaveLessonGoodsId: false,
      // 详情属性显示数据
      attrDetailList: '',
      // 报名详情
      historyData: [],
      tableKeys: [
        { prop: 'time', label: '日期', minWidth: '100', filter: filterTime },
        { prop: 'status', label: '状态变更', minWidth: '100', filter: filterStatus }
      ]
    }
  },

  async mounted() {
    const { id, name, sku_id, price } = this.$route.query
    if (id) {
      this.type = 'edit'
      this.isUpdate = true
      this.id = id
      this.getInfo()
    } else {
      await this.getOrderAttributes()
      this.lessonName = name
      // this.lessonSku_id = sku_id
      // this.lessonPrice = price
      const really_sku_id = await this.courseGetInfo(sku_id)
      // if (!really_sku_id) {
      //   this.skuOpenType = 'lesson'
      // } else {
      //   this.isHaveLessonGoodsId = true
      // }
      this.aGoods.push({
        aSkuId: really_sku_id,
        aQuantity: 1,
        name,
        aPayment: parseFloat(price, 10)
      })
    }
  },

  watch: {
    isShowGoods() {
      console.log(this.isShowGoods)
    }
  },

  methods: {
    ...mapMutations(['setTabRoutes']),

    async getOrderAttributes() {
      const { code, data } = await this.$api.utilsGetAllClasses({
        aMerchantId: this.aFirmId,
        aType: '2'
      })
      if (code === 0) {
        this.formatAttrAndClassData(data.list)
      }
    },

    async getInfo() {
      const { code, data } = await this.$api.orderGetInfo({
        aId: this.id
      })
      if (code === 0) {
        console.log(data)
        this.historyData = data.status_history || []
        this.buyer_name = data.buyer_name
        this.seller = data.seller_id
        this.sellerName = data.seller_name
        this.phone = data.buyer_phone
        this.price = data.payment
        this.userId = data.buyer_id
        this.formatDetailAttrData(data.attrs)
        // 根据必须和非必须，进行分开格式化
        // this.formatInfoData(data.attrs.filter(v => v.is_require === '1'))
        // this.contactAttrData()
        // this.$refs.attrList.formatDetailDataToAttrList(data.attrs.filter(v => v.is_require !== '1'))
        // 填充 aGoods 数据
        const lessonData = data.detail_list[0]
        this.lessonName = lessonData.goods_name
        console.log(this.lessonName, lessonData)
        this.aGoods[0] = {
          aSkuId: lessonData.sku_id,
          aQuantity: 1,
          name: lessonData.goods_name,
          aPayment: lessonData.payment
        }
        const goodData = data.detail_list[1]
        if (goodData) {
          this.aGoods[1] = {
            aSkuId: goodData.sku_id,
            aQuantity: 1,
            name: goodData.goods_name,
            aPayment: goodData.price
          }
        }
        this.isShowGoods = ((goodData && goodData.goods_name) || '') !== data.order_name
        console.log(this.isShowGoods)
        this.getUserDetail(data.buyer_id)
      }
    },

    async getUserInfo() {
      const phone = this.phone
      console.log(phone)
      if (!window.$tools.regexp.phone.test(phone)) {
        return this.__notify('警告', '请输入正常的手机号', 'warning')
      }
      const { code, data } = await this.$api.crmGetIntents({
        aFirmId: this.aFirmId,
        aPhone: phone
      })
      if (code === 0) {
        if (data.list[0]) {
          this.buyer_name = data.list[0].short_name
          this.userId = data.list[0].id
          this.getUserDetail(data.list[0].id)
        } else {
          return this.__notify('导入客户资料', '暂无此手机号', 'info')
        }
      }
    },

    async getUserDetail(aId) {
      const { code, data } = await this.$api.crmGetIntentInfo({
        aId
      })
      if (code === 0) {
        console.log(data)
        this.formatCrmAttrsData(data.attrs)
      }
    },

    // 格式化用户属性数据，只需要显示
    formatCrmAttrsData(data) {
      const arr = []
      data.forEach(attr => {
        let content = ''
        const isHaveChildClasses = attr.values.some(classes => {
          if (classes.pid) {
            content = classes.value_title
            return true
          }
          return false
        })
        if (!isHaveChildClasses) content = attr.values[0].value_title
        arr.push({ ...attr, content })
      })
      console.log(this.attrDetailList)
      this.userAttrList = arr.concat(...this.attrDetailList)
    },

    showLessonDialog() {
      this.$refs.lessonDialog.show()
    },

    showPriceDialog() {
      this.$refs.priceDialog.show()
    },

    showStaffDialoog() {
      this.$refs.staffDialog.show()
    },

    skuDialog() {
      this.$refs.skuDialog.show()
    },

    async getLessonTitle({ name, sku_id, price }) {
      this.lessonName = name
      // const sku_id = await this.courseGetInfo(id)
      // if (!sku_id) {
      //   this.skuOpenType = 'lesson'
      //   return false
      // }
      this.aGoods[0] = {
        aSkuId: sku_id,
        aQuantity: 1,
        name,
        aPayment: price
      }
      this.isShowGoods = (this.aGoods[1] ? this.aGoods[1].name : '') !== this.lessonName
    },

    async getPrice({ selectPrice, sku_id, name }) {
      this.price = parseFloat(selectPrice, 10)
      // const sku_id = await this.courseGetInfo(id)
      // if (!sku_id) {
      //   this.skuOpenType = 'price'
      //   return false
      // }
      this.aGoods.push({})
      this.aGoods[1] = {
        aSkuId: sku_id,
        aQuantity: 1,
        name,
        aPayment: selectPrice
      }
      this.isShowGoods = name !== this.lessonName
      console.log(this.isShowGoods, this.aGoods.length)
    },

    getStaff({ name, staff_id }) {
      console.log(name, staff_id)
      this.seller = staff_id
      this.sellerName = name
    },

    checkParams() {
      const { userId, seller } = this
      let msg = ''
      if (!userId) {
        msg = '请填充客户资料'
      } else if (!seller) {
        msg = '请选择销售员'
      }
      if (msg) {
        this.__notify('警告', msg, 'warning')
      }
      return !msg
    },

    async create() {
      if (this.ifRequesting) return false
      const isOk = this.checkParams()
      if (!isOk) return false
      this.ifRequesting = true
      const params = {
        aId: this.aFirmId,
        aGoods: this.aGoods,
        aBuyerId: this.userId,
        aSellerId: this.seller,
        aAttrs: this.formatOutputData()
      }
      const { code } = await this.$api[this.type === 'add' ? 'orderCreate' : 'orderModify'](params)
      this.ifRequesting = false
      if (code === 0) {
        this.__notify('提示', this.type === 'add' ? '添加成功' : '修改成功')
        this.setTabRoutes({ type: 'add', obj: this.getRouterInfoAccordingName('apply') })
        this.$router.push({ name: 'apply' })
      }
    },

    closeGood() {
      this.aGoods.pop()
    },

    // 获取课程的 sku_id
    async courseGetInfo(id) {
      const { code, data } = await this.$api.courseGetDetail({ aId: id })
      if (code === 0) {
        // if (data.skus.length > 1) {
        //   this.skuData = data.skus
        //   this.$nextTick(() => {
        //     this.skuDialog()
        //   })
        //   return false
        // }
        return data.skus[0].id
      }
      return ''
    },

    getSkuFromDialog(data) {
      // this.selectSkuId = data
      if (this.skuOpenType === 'lesson') {
        this.aGoods[0].id = data
      } else if (this.skuOpenType === 'price') {
        this.aGoods[1].id = data
      }
    },

    /**
     * 格式化详情的属性数据，只显示
     */
    formatDetailAttrData(data) {
      const arr = []
      data.forEach(attr => {
        const attrObj = {
          id: attr.id,
          name: attr.name,
          classes: []
        }
        attr.values.forEach(v => {
          attrObj.classes.push(v.value_title)
        })
        attrObj.content = attrObj.classes.join(',')
        arr.push(attrObj)
      })
      this.attrDetailList = arr
    }
  }
}
</script>

<style lang='less'>
.m-courseSignUp {
  max-width: 1200px;
  .w100 {
    width: 100%;
  }
  &_top {
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 20px;
    padding-top: 20px;
    font-size: 14px;
    .list {
      display: flex;
      flex-wrap: wrap;
    }
    .item {
      width: 33.3333%;
      padding: 0 20px 20px;
      box-sizing: border-box;
    }
    .grid-content {
      display: flex;
      align-items: flex-start;
      .name {
        padding-right: 20px;
        width: 60px;
        white-space: nowrap;
      }
      .value {
        padding-right: 20px;
      }
    }
    .goods-item {
      display: flex;
      width: 100%;
      .key {
        width: 80px;
        padding-right: 20px;
        text-align: right;
      }
      .value {
        // display: flex;
        text-align: center;
        .item {
          display: flex;
          width: 100%;
          align-items: center;
          span {
            width: 100px;
            display: block;
          }
        }
      }
    }
  }
  &_bottom {
    & > .el-form--inline {
      display: flex;
      flex-wrap: wrap;
    }
    & > .el-form--inline > .el-form-item {
      display: flex;
      align-items: center;
      margin-right: 0;
      padding-right: 10px;
      box-sizing: border-box;
      width: 100%;
      & > .el-form-item__content {
        display: flex;
        align-items: center;
        flex: 1;
        & > .el-select {
          flex: 1;
        }
      }
    }
  }

  // 用户信息列表
  &_userAttrs {
    display: flex;
    flex-wrap: wrap;
    font-size: 14px;
    color: #606266;
    .item {
      width: 50%;
      display: flex;
      align-items: center;
      padding-bottom: 22px;
      .key {
        width: 120px;
        padding-right: 10px;
        box-sizing: border-box;
        text-align: right;
        display: block;
      }
    }
  }

  &_autoAttr {
    width: 100%;
    display: flex;
    align-items: center;
    .el-icon-close {
      margin-left: 20px;
    }
    &_wrap {
      .form-content {
        width: 100%;
      }
    }
  }
  .createTheFormItem {
    .el-checkbox-group {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      width: 100%;
    }
    .el-checkbox {
      // flex: 1;
      width: 50%;
      display: flex;
      align-items: center;
      padding-right: 10px;
      box-sizing: border-box;
      &:nth-child(n+3) {
          padding-top: 10px;
        }
    }
    .el-checkbox+.el-checkbox {
      margin-left: 0;
    }
    .el-input {
      // width: auto;
    }
  }

  // dialog
  &_dialog {
    .u-attr-search {
      display: flex;
      flex-wrap: wrap;
      .list {
        width: 100%;
      }
      .el-form-item {
        width: 50%;
        display: flex;
        align-items: center;
        margin-right: 0;
        box-sizing: border-box;
        overflow: hidden;
      }
      .el-form-item__content {
        flex: 1;
      }
      .el-select {
        width: 100%;
        flex: 1;
      }
    }
  }
}
</style>